package com.luwanglin.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luwanglin.commonutils.R;
import com.luwanglin.commonutils.ResultCode;
import com.luwanglin.eduservice.client.VodClient;
import com.luwanglin.eduservice.entity.EduVideo;
import com.luwanglin.eduservice.mapper.EduVideoMapper;
import com.luwanglin.eduservice.service.EduVideoService;
import com.luwanglin.commonutils.exception.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * cource subsection  课程视频 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-05-13
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {
    @Autowired
    private VodClient vodClient;


    @Override
    public boolean removeByCourseId(String courseId) {
        QueryWrapper<EduVideo> queryWrapperVideo = new QueryWrapper<>();
        queryWrapperVideo.eq("course_id", courseId);
        queryWrapperVideo.select("video_source_id");
        List<EduVideo> videoList = baseMapper.selectList(queryWrapperVideo);
        //得到所有视频列表的云端原始视频id
        List<String> videoSourceIdList = new ArrayList<>();
        for (EduVideo video : videoList) {
            String videoSourceId = video.getVideoSourceId();
            if (!StringUtils.isEmpty(videoSourceId)) {
                videoSourceIdList.add(videoSourceId);
            }
        }
        //调用vod服务删除远程视频
        if (videoSourceIdList.size() > 0) {
            vodClient.removeVideoList(videoSourceIdList);
        }
        QueryWrapper<EduVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", courseId);
        int count = baseMapper.delete(queryWrapper);
        return count > 0;
    }

    @Override
    public void completeDelete(String id) {
        EduVideo eduVideo = baseMapper.selectById(id);
        if (!StringUtils.isEmpty(eduVideo.getVideoSourceId())) {
            R r = vodClient.removeVideo(eduVideo.getVideoSourceId());
            if (r.getCode().equals(ResultCode.ERROR.getCode())) {
                throw new GuliException(20001, "delete video failed hystrix");
            }
        }
        baseMapper.deleteById(id);
    }
}
